<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\BaseController;
use app\common\Attribute;
use app\model\Admin;
use app\model\AdminRole;
use think\facade\View;

#[Attribute(title: "管理员")]
class AdminController extends BaseController
{
    #[Attribute(isAuth: true, isPage: true, title: "查询")]
    public function query()
    {
        if (request()->isPost()) {
            $all = request()->param();
            $order = ["id" => "desc"];
            if (isset($all["order"]) && $all["order"] != null) {
                $order = [$all["order"]["field"] => $all["order"]["order"]];
            }
            $data = Admin::field("id,rid,name,avatar,username,blacklist,create_time,update_time")
                ->order($order)
                ->withJoin(['role' => ['role.name' => 'role']], 'left')
                ->paginate([
                    "list_rows" => $all["limit"],
                    "page" => $all["page"]
                ])->toArray();
            return json([
                "code" => 0,
                "msg" => "获取成功",
                "count" => $data["total"],
                "data" => $data["data"],
            ]);
        }
        return View::fetch();
    }

    #[Attribute(isAuth: true, isPage: true, title: "添加")]
    public function add()
    {
        $parent_data = AdminRole::select();
        View::assign(name: ["parent_data" => selectTree($parent_data->toArray())]); //顶级选项
        if (request()->isPost()) {
            $all = request()->param();
            try {
                validate(\app\admin\validate\AdminValidate::class)
                    ->scene("add")
                    ->check($all);
                $all["password"] = password_hash($all["password"], PASSWORD_DEFAULT);
                $res = Admin::create($all);
                if ($res) {
                    return success("操作成功");
                } else {
                    return error("操作失败");
                }
            } catch (\think\exception\ValidateException $e) {
                return error(msg: "验证失败", data: $e->getError());
            }
        }
        return View::fetch();
    }

    #[Attribute(isAuth: true, isPage: false, title: "编辑")]
    public function edit()
    {
        if (request()->isGet()) {
            $id = request()->get('id');
            $find = Admin::find($id);
            View::assign("find", $find);
            $parent_data = AdminRole::select();
            View::assign(name: ["parent_data" => selectTree($parent_data->toArray())]); //顶级选项
        }
        if (request()->isPost()) {
            $all = request()->param();
            if ($all["rid"] <= 0) {
                return error("操作无效");
            }
            try {
                validate(\app\admin\validate\AdminValidate::class)
                    ->scene("edit")
                    ->check($all);
                if (isset($all["password"]) && $all["password"] != "") {
                    $all["password"] = password_hash($all["password"], PASSWORD_DEFAULT);
                } else {
                    unset($all["password"]);
                }
                $res = Admin::update($all);
                if ($res) {
                    return success("操作成功");
                } else {
                    return error("操作失败");
                }
            } catch (\think\exception\ValidateException $e) {
                return error(msg: "验证失败", data: $e->getError());
            }
        }
        return View::fetch();
    }

    #[Attribute(isAuth: true, isPage: false, title: "删除")]
    public function del()
    {
        if (request()->isDelete()) {
            $all = request()->param();
            $allFild = Admin::where("id", "in", $all["id"])->select();
            $start = true;
            foreach ($allFild as $k => $v) {
                if ($v["rid"] == 0) {
                    $start = false;
                }
            }
            if ($start) {
                $res = Admin::destroy($all["id"]);
                if ($res) {
                    return success("操作成功");
                } else {
                    return error("操作失败");
                }
            } else {
                return error("非法操作");
            }
        }
    }
}
